package com.aliengen.thingple.driverapp.ui.activities;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.aliengen.thingple.driverapp.R;
import com.aliengen.thingple.driverapp.data.local.EventModel;
import com.aliengen.thingple.driverapp.data.models.CylinderTag;
import com.aliengen.thingple.driverapp.data.models.Report;
import com.aliengen.thingple.driverapp.device.BatchReadThread;
import com.aliengen.thingple.driverapp.device.CMCHandler;
import com.aliengen.thingple.driverapp.ui.adapters.CylindersListAdapter;
import com.aliengen.thingple.driverapp.ui.fragments.CylindersListFragment;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@EActivity(R.layout.activity_tag_reading)
public class TagReadingActivity extends AbstractBaseActivity implements BatchReadThread.ReadingListener, CylindersListFragment.OnListFragmentListener {

    @Extra("report")
    Report report;

    @ViewById
    protected TextView truckTitle;

    @ViewById
    protected TextView customerTitle;

    @ViewById
    protected TextView customerAddressTitle;

    @ViewById
    Button startButton;

    @ViewById
    Button stopButton;

    @ViewById
    protected TextView cylindersCount;

    @FragmentById
    CylindersListFragment cylinders_list;

    protected BatchReadThread readThread = null;

    @AfterViews
    public void init()
    {
        setTextView(truckTitle, R.string.truck_plate_number, report.truck.getPlateNumber());
        setTextView(customerTitle, R.string.customer_name, report.customer.name);
        setTextView(customerAddressTitle, R.string.customer_address, report.customer.address);

        setCylinderCount(0);
        BatchReadThread.cylindersList.clear();

        prepareReader();
    }

    @Override
    protected void onResume() {
        super.onResume();
        prepareReader();
    }

    protected void prepareReader()
    {
        if(report.operation.compareTo("delivery") == 0)
        {
            BatchReadThread.operationId = 13; // Delivery
        }
        else
        {
            BatchReadThread.operationId = 12; // Pickup
        }

        mApplication.getHandler().setActivity(this);

        mApplication.getHandler().setOnEventListener(new CMCHandler.OnEventListener() {
            @Override
            public void onPressDown() {
                startReading();
            }

            @Override
            public void onPressUp() {
                stopReading();
            }

            @Override
            public void onReceiveData() {
                updateList();
            }
            @Override
            public void onRead(String data) {
            }

            @Override
            public void onReadFailed() {
            }

            @Override
            public void onWrite() {
            }

            @Override
            public void onWriteFailed() {
            }

            @Override
            public void onTagSelected() {
            }

            @Override
            public void onTagSelectFailed() {

            }
        });

        BatchReadThread.truckTag = this.report.truck;
    }

    public void setCylinderCount(Integer count) {
        setTextView(cylindersCount, R.string.cylinders_count, count.toString());
    }

    public void updateList() {
        final CylindersListAdapter adapter = cylinders_list.getAdapter();
        adapter.updateList(BatchReadThread.cylindersList);
        setCylinderCount(adapter.getItemCount());

        /*
        ArrayList<CylinderTag> list = new ArrayList<CylinderTag>(BatchReadThread.cylindersList.values());
        AsyncTagUpdate async = new AsyncTagUpdate();
        async.setApplication(mApplication);

        async.setOnExecuteListener(new AsyncTagUpdate.OnExecuteListener() {
            @Override
            public void onPostExecute() {
                showToast(R.string.cylinders_synchronized);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onProgressUpdate() {

            }

            @Override
            public void onMessage(String message) {
                showToast(message);
            }
        });

        if(!this.alert.isVisible() && !this.alert.isAdded()) {
            Iterator<CylinderTag> iter = list.iterator();
            Boolean hasMaintenanceNeeded = false;
            while (iter.hasNext()) {
                CylinderTag t = iter.next();
                if (t.hasProblem()) {
                    hasMaintenanceNeeded = true;
                    break;
                }
            }

            if (hasMaintenanceNeeded) {
                Bundle args = new Bundle();
                args.putString("title", getResources().getString(R.string.cylinders_alert_title));
                args.putString("message", getResources().getString(R.string.cylinders_alert_content));
                alert.setArguments(args);
                alert.show(getFragmentManager(), "tag");
            }
        }

        async.execute(list);
        */
    }

    /**
     * Reading tags
     */
    public Boolean validate(CylinderTag tag)
    {
        return true;
    }

    public void onReadingException(Exception e)
    {
    }

    /**
     * Controls
     */
    public void startReading() {
        if(readThread != null && readThread.isAlive())
        {
            showToast("Reading already launched!");
            return;
        }

        startButton.setVisibility(View.GONE);
        stopButton.setVisibility(View.VISIBLE);

        readThread = new BatchReadThread(mApplication, this);
        readThread.start();
    }

    public void stopReading() {
        if(readThread == null)
        {
            showToast("Reading already stopped!");
            return;
        }

        readThread.stopReading();
        stopButton.setVisibility(View.GONE);
        startButton.setVisibility(View.VISIBLE);
    }


    public void onClickStart(View v) {
        startReading();
    }

    public void onClickStop(View v) {
        stopReading();
    }

    public void onClickNext(View v) {
        stopReading();

        List<CylinderTag> list = cylinders_list.getAdapter().getList();
        for(CylinderTag tag : list)
        {
            EventModel event = new EventModel();
            event.huashen_number = tag.getReference();
            event.operation_id = BatchReadThread.operationId;
            event.cylinder_type = "cylinder";
            event.truck_id = report.truck.getTruckId();
            event.truck_plate_number = report.truck.getPlateNumber();
            event.anomaly_phase = "";
            event.anomaly_inspection = "";
            event.save();

        }

        Intent nextScreen = new Intent(getApplicationContext(), AnomalyListActivity_.class);
        nextScreen.putExtra("report", report);
        report.cylinders = cylinders_list.getAdapter().getList();
        startActivity(nextScreen);
        this.finish();
    }

    @Override
    public void onListInteraction(CylinderTag item) {

    }
}
